#!/usr/bin/env python3
# -*- coding=utf-8 -*-
# 本脚由亁颐堂现任明教教主编写，用于乾颐盾Python课程！
# 教主QQ:605658506
# 亁颐堂官网www.qytang.com
# 教主技术进化论拓展你的技术新边疆
# https://ke.qq.com/course/271956?tuin=24199d8a

# import django
# import os
# os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'DevNet2019.settings')
# django.setup()
from devnet.models import Devicedb, Devicecpu, Devicemem, LastAlarmCPU, LastAlarmMEM, Thresholdcpu, Thresholdmem
from devnet.modules.qyt_devnet_0_snmp_get import get_mem_cpu
from datetime import datetime
from devnet.modules.qyt_devnet_0_smtp import alarm_msg


def get_cpu_threshold():
    try:
        cpu_threshold_obj = Thresholdcpu.objects.get(id=1)
        threshold = cpu_threshold_obj.cpu_threshold
        if not threshold:
            return False
        else:
            interval = cpu_threshold_obj.alarm_interval
            if not interval:
                return False
            else:
                return threshold, interval
    except Thresholdcpu.DoesNotExist:
        return False


def get_mem_threshold():
    try:
        mem_threshold_obj = Thresholdmem.objects.get(id=1)
        threshold = mem_threshold_obj.mem_threshold
        if not threshold:
            return False
        else:
            interval = mem_threshold_obj.alarm_interval
            if not interval:
                return False
            else:
                return threshold, interval
    except Thresholdmem.DoesNotExist:
        return False


def get_device_cpu_last_alarm(device_obj):
    if not get_cpu_threshold():
        return False
    interval = get_cpu_threshold()[1]
    try:
        last_alarm = LastAlarmCPU.objects.get(device=device_obj).last_alarm_datetime
        if (datetime.now() - last_alarm).seconds > interval * 60:
            l = LastAlarmCPU.objects.get(device=device_obj)
            l.last_alarm_datetime = datetime.now()
            l.save()
            return True
        else:
            return False
    except LastAlarmCPU.DoesNotExist:
        c = LastAlarmCPU(device=device_obj)
        c.save()
        return True


def get_device_mem_last_alarm(device_obj):
    if not get_mem_threshold():
        return False
    interval = get_mem_threshold()[1]
    try:
        last_alarm = LastAlarmMEM.objects.get(device=device_obj).last_alarm_datetime
        if (datetime.now() - last_alarm).seconds > interval * 60:
            l = LastAlarmMEM.objects.get(device=device_obj)
            l.last_alarm_datetime = datetime.now()
            l.save()

            return True
        else:
            return False
    except LastAlarmMEM.DoesNotExist:
        c = LastAlarmMEM(device=device_obj)
        c.save()
        return True


def get_mem_cpu_todb():
    for device in Devicedb.objects.all():
        try:
            if device.reachable.all().order_by('-id')[0].snmp_reachable:
                mem_percent, cpu_percent = get_mem_cpu(device.ip)
                if cpu_percent:
                    if get_cpu_threshold():
                        if cpu_percent > get_cpu_threshold()[0]:
                            if get_device_cpu_last_alarm(device):
                                alarm_msg("设备{0} CPU利用率超过阈值{1}%!当前的CPU利用率为{2}%".format(device.name, get_cpu_threshold()[0], cpu_percent))

                    c = Devicecpu(device=device,
                                  cpu_usage=cpu_percent)
                    c.save()
                else:
                    c = Devicecpu(device=device,
                                  cpu_usage=0)
                    c.save()

                if mem_percent:
                    if get_mem_threshold():
                        if mem_percent > get_mem_threshold()[0]:
                            if get_device_mem_last_alarm(device):
                                alarm_msg("设备{0} 内存利用率超过阈值{1}%!当前的内存利用率为{2}%".format(device.name, get_mem_threshold()[0], mem_percent))

                    m = Devicemem(device=device,
                                  mem_usage=mem_percent)
                    m.save()
                else:
                    m = Devicemem(device=device,
                                  mem_usage=0)
                    m.save()
            else:
                continue
        except Exception as e:
            print(e)
            continue


if __name__ == '__main__':
    get_mem_cpu_todb()
